package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /*A. 获取当前登录用户，为购物车对象赋值

      B. 根据当前登录用户ID 及 本次添加的菜品ID/套餐ID，   查询  select   购物车数据是否存在

      C. 如果已经存在，就在原来数量基础上加1  update

      D. 如果不存在，则添加到购物车，数量默认就是1    save   */

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    @Transactional
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("购物车数据:{}",shoppingCart);

        //线程添加用户id
        shoppingCart.setUserId(BaseContext.getCurrentId());

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());

        //是否获取 来拼接sql
        Long dishId = shoppingCart.getDishId();
        if(dishId != null){
            //添加到购物车的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }else{
            //添加到购物车的是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        //查询当前菜品或者套餐是否在购物车中
        //SQL:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        ShoppingCart one = shoppingCartService.getOne(queryWrapper);

        if(one != null){
            //如果已经存在，就在原来数量基础上加一
            Integer number = one.getNumber();
            one.setNumber(number + 1);
            shoppingCartService.updateById(one);
        }else{
            //如果不存在，则添加到购物车，数量默认就是一
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            one = shoppingCart;
        }
        return R.success(one);
    }


    /**
     * 查看购物车  根据当前登录用户ID
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看购物车");

        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        qw.orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shoppingCartService.list(qw);
        return R.success(list);
    }

    /**
     * 删除购物车  请求参数  json  dishId 或  setmealId
     * @param shoppingCart
     * @return
     */
    //先查询  select   哪个用户的 菜品/套餐id   数量-1==0就 从购物车remove  否则  update
    @PostMapping("/sub")
    @Transactional
    public R<ShoppingCart> delete(@RequestBody ShoppingCart shoppingCart){
        //菜品或者套餐id 查询出当前ShoppingCart数据
        // 如果是菜品：select * from shopping_cart where dish_id = ? and user_id = ?
        // 如果是套餐：select * from shopping_cart where setmeal_id = ? and user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        Long userId = BaseContext.getCurrentId();

        qw.eq(ShoppingCart::getUserId,userId);//where user_id =?

        Long dishId = shoppingCart.getDishId();
        if(dishId!=null){//是菜品
            qw.eq(ShoppingCart::getDishId,dishId);// dish_id = ?
        }else {// 是套餐
            qw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());// setmeal_id = ?
        }

        ShoppingCart one = shoppingCartService.getOne(qw);
        // number -1 然后操作：
        Integer number = one.getNumber();
        number--;
        one.setNumber(number);
        if(number>0){
            // >0  update更新 update set number=? where id = ?
            shoppingCartService.updateById(one);
        }else {
            // <= 0  如何操作？ delete from shopping_cart where dish_id=? and user_id = ?
            shoppingCartService.remove(qw);
        }
        return R.success(one);
    }

    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        //delete from shopping_cart where user_id = ?
        qw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(qw);
        return R.success("购物车已清空");
    }

}
